package com.liaoban.app.ui.base;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.liaoban.app.R;
import com.liaoban.app.api.type.PayIndex;
import com.liaoban.app.api.type.PayIndex2Request;
import com.liaoban.app.api.type.PayResult;
import com.liaoban.app.api.type.WxPayIndex2;
import com.liaoban.app.api.type.event.PaySucEvent;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.util.WXPayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

/**
 * Created by ybc on 2018/4/26 0026.
 * 支付基类
 */

public abstract class BasePayActivity extends BaseToolbarActivity {
    private static final int SDK_PAY_FLAG = 1;
    private String mOrderId;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    // TODO: 2018/8/9 0009 先注释
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paySuc();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastHelper.show(BasePayActivity.this, R.string.pay_fail);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
    }

    /**
     * 支付宝支付
     */
    protected void zfbPay(PayIndex.MoneyBean moneyBean) {
        showRunningDialog();
        PayIndex2Request payIndex2Request = new PayIndex2Request();
        payIndex2Request.setMbId(moneyBean.getMbId() + "");
        payIndex2Request.setDealType(PayIndex2Request.TYPE_ALI);
        startTask(CommonBiz.getInstance().payIndex2(payIndex2Request), stringBaseResponse -> {
            Runnable payRunnable = () -> {
                PayTask payTask = new PayTask(this);
                Map<String, String> result = payTask.payV2(stringBaseResponse.data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            };
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        });
    }

    /**
     * 微信支付
     */
    protected void wxPay(PayIndex.MoneyBean moneyBean) {
        showRunningDialog();
        PayIndex2Request payIndex2Request = new PayIndex2Request();
        payIndex2Request.setMbId(moneyBean.getMbId() + "");
        payIndex2Request.setDealType(PayIndex2Request.TYPE_WX);
        startTask(CommonBiz.getInstance().payIndex2Wx(payIndex2Request), pay -> {
            WxPayIndex2 wxPayIndex2 = pay.data;
            WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
            builder.setAppId(Constant.WEIXIN_APPID)
                    .setPartnerId(wxPayIndex2.getPartnerid())
                    .setPrepayId(wxPayIndex2.getPrepayid())
                    .setPackageValue("Sign=WXPay")
                    .setNonceStr(wxPayIndex2.getNoncestr())
                    .setTimeStamp(wxPayIndex2.getTimestamp() + "")
                    .setSign(wxPayIndex2.getSign())
                    .build().toWXPayNotSign(BasePayActivity.this, Constant.WEIXIN_APPID);
        });
    }

    @Override
    protected void onDestroy() {
        mHandler.removeMessages(SDK_PAY_FLAG);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySucEvent(PaySucEvent paySucEvent) {
        finish();
    }

    public abstract void paySuc();
}
